package com.anbang.website.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.anbang.website.service.CmsHelper;
import com.anbang.website.service.OrderHelper;
import com.anbang.website.service.ProCateHelper;
import com.anbang.website.service.ProductionsHelper;
import com.anbang.website.service.ShoppingCartHelper;
import com.anbang.website.service.SystemServiceHelper;
import com.anbang.website.utils.Constant;
import com.anbang.website.utils.SystemLoginUtils;
import com.anbang.website.vo.BusCms;
import com.anbang.website.vo.Order;
import com.anbang.website.vo.Productions;
import com.anbang.website.vo.ProductionsCategory;
import com.anbang.website.vo.ResData;
import com.anbang.website.vo.ShoppingCart;
import com.anbang.website.vo.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import net.sf.json.JSONObject;

@Controller
public class IndexController extends BaseController {
	@RequestMapping("index")
	public String index(HttpServletRequest request, Model model) {
		String pageNo = request.getParameter("pageNo");
		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "8";
		}

		JSONObject obj = ProductionsHelper.prodList("", "3", "", Integer.valueOf(pageNo), Integer.valueOf(pageSize));
		if(obj.getString("code").equals(ResData.RES_CODE_SUCCESS)){
			// 使用gson 转化返回的json字符串
			Gson gson = new GsonBuilder().create();
			List<Productions> retList = gson.fromJson(obj.getJSONObject("data").getString("productionsList"),
					new TypeToken<List<Productions>>() {
					}.getType());
			model.addAttribute("prodList", retList);
			model.addAttribute("pageNo", obj.getJSONObject("data").getInt("pageNo"));
			model.addAttribute("pageSize", obj.getJSONObject("data").getInt("pageSize"));
			model.addAttribute("count", obj.getJSONObject("data").getInt("count"));
		}
		return "/index";
	}

	@RequestMapping("login")
	public String login(HttpServletRequest request, Model model) {
		String sucessUrl = request.getParameter("successUrl");
		if(StringUtils.isNotEmpty(sucessUrl)){
			model.addAttribute("sucessUrl", sucessUrl);
		}		
		return "/login";
	}

	@RequestMapping("dologin")
	public String doLogin(HttpServletRequest request, Model model) {
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");
		String sucessUrl = request.getParameter("successUrl");
		
		JSONObject ret = SystemServiceHelper.login(userName, passWord);
		if (ret.getString("code").equals(ResData.RES_CODE_SUCCESS)) {
			JSONObject user = ret.getJSONObject("data").getJSONObject("user");
			HttpSession session = request.getSession();
			session.setAttribute("userId", user.getLong("id"));
			session.setAttribute("name", user.getString("name"));
			session.setAttribute("mobile", user.getString("mobile"));
			session.setAttribute("loginName", user.getString("loginName"));
			session.setAttribute("businesspersonid", user.getLong("businesspersonid"));
			session.setAttribute("customerid", user.getLong("customerid"));
			if(StringUtils.isNotEmpty(sucessUrl)){
				return "redirect:"+sucessUrl;
			}
			else{
				return "redirect:/index";
			}
		} else {
			if(StringUtils.isNotEmpty(sucessUrl)){
				model.addAttribute("sucessUrl", sucessUrl);
			}
			model.addAttribute("error", ret.getString("msg"));
			model.addAttribute("username", userName);
			model.addAttribute("password", passWord);
			return "/login";
		}

	}

	@RequestMapping("logout")
	public String logout(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		session.invalidate();
		return "redirect:/index";
	}
	
	@RequestMapping("modpwd")
	public String modPwd() {
		
		return "/mod_pass";
	}
	
	@RequestMapping("domodpwd")
	public String doModPwd(HttpServletRequest request, Model model) {
		String loginName = request.getParameter("loginName");
		String oldpassword = request.getParameter("oldpassword");
		String newpassword = request.getParameter("newpassword");
		JSONObject ret = SystemServiceHelper.modpwd(loginName, oldpassword, newpassword);
		if (ret.getString("code").equals(ResData.RES_CODE_SUCCESS)) {
			model.addAttribute("success", "1");
			return "/mod_pass";
		}else{
			model.addAttribute("error", ret.getString("msg"));
		}
		
		return "/mod_pass";
	}

	/****************************************************************************
	 * 订单功能_开始
	 ***************************************************************************/
	/**
	 * 购物车商品生成订单
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("genorder")
	public String genOrder(HttpServletRequest request, Model model){
		//判断session是否失效，如失效需重新登录
		Long userId = SystemLoginUtils.getLoginUserId(request);
		if (null == userId){
			return "redirect:" + Constant.DAFAULT_LOGIN_URL;
		}
		
		String cartIds[] = (String[])request.getParameterValues("id");//购物车id数组
		String ids[] = (String[])request.getParameterValues("prodId");//商品id数组
		String nums[]= (String[])request.getParameterValues("num");//商品数量数组
		Long customerId = SystemLoginUtils.getCustomerId(request);//取客户id
		Long businesspersonId = SystemLoginUtils.getBusinesspersonId(request);//业务联系人id
		
		//保存提交订单
		JSONObject ret = OrderHelper.submitOrder(ids, nums, userId, customerId, businesspersonId,cartIds);
		if (ret.getString("code").equals(ResData.RES_CODE_SUCCESS)) {
			return "redirect:/myorder";
		}
		
		return "/order/my_order";
	}

	/**
	 * 显示我的订单：查询我的订单列表数据
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("myorder")
	public String myOrder(@ModelAttribute("order") Order order, HttpServletRequest request, Model model){
		//判断session是否失效，如失效需重新登录
		Long userId = SystemLoginUtils.getLoginUserId(request);
		if (null == userId){
			return "redirect:" + Constant.DAFAULT_LOGIN_URL;
		}
		
		/* 分页处理*/
		String pageNo = request.getParameter("pageNo");
		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "15";
		}		
		
		//构造order属性
		order.setCreateBy(new User(userId));
		
		//根据登陆用户查询订单数据
		JSONObject obj = OrderHelper.myOrder(order, pageNo, pageSize);
		if(obj.getString("code").equals(ResData.RES_CODE_SUCCESS)){
			//使用gson 转化返回的json字符串
			Gson gson = new GsonBuilder().create();
			List<Order> list = gson.fromJson(obj.getJSONObject("data").getString("orderList"),
					new TypeToken<List<Order>>() {
					}.getType());	
			
			model.addAttribute("orderList", list);
			model.addAttribute("approveEnum", Constant.approveEnum());//审批状态
			model.addAttribute("order", order);
			model.addAttribute("pageNo", obj.getJSONObject("data").getInt("pageNo"));
			model.addAttribute("pageSize", obj.getJSONObject("data").getInt("pageSize"));
			model.addAttribute("count", obj.getJSONObject("data").getInt("count"));
		}
		
		return "/order/my_order";
	}
	/****************************************************************************
	 * 订单功能_结束
	 ***************************************************************************/	
	/****************************************************************************
	 * 购物车功能_开始
	 ***************************************************************************/
	@RequestMapping("myshopcart")
	public String myShopCart(HttpServletRequest request, Model model){
		//判断session是否失效，如失效需重新登录
		Long userId = SystemLoginUtils.getLoginUserId(request);
		if (null == userId){
			return "redirect:" + Constant.DAFAULT_LOGIN_URL;
		}
		
		JSONObject obj = ShoppingCartHelper.myShopCart(userId);//登录用户的购物车
		if(obj.getString("code").equals(ResData.RES_CODE_SUCCESS)){
			//使用gson 转化返回的json字符串
			Gson gson = new GsonBuilder().create();
			List<ShoppingCart> list = gson.fromJson(obj.getJSONObject("data").getString("cartList"),
					new TypeToken<List<ShoppingCart>>() {
					}.getType());	
			
			model.addAttribute("cartList", list);
		}
		
		return "/order/my_shop_cart";
	}
	
	/**
	 * 加入商品到购物车
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("addtocart")
	@ResponseBody
	public String addToCart(HttpServletRequest request, HttpServletResponse response){
		//判断session是否失效，如失效需重新登录
		Long userId = SystemLoginUtils.getLoginUserId(request);
		if (null == userId){
			return ResData.RES_CODE_TIMESTAMP_EXPIRED;
		}
		
		//获取页面传过来的参数.  
		String prodId     = request.getParameter("id");//商品id
		String num        = request.getParameter("num");//商品数量
		
		//取客户id
		Long customerId = SystemLoginUtils.getCustomerId(request);
		
		JSONObject ret = ShoppingCartHelper.addToCart(prodId, num, String.valueOf(userId), customerId);//
		if (ret.getString("code").equals(ResData.RES_CODE_SUCCESS)) {
			return "成功加入到购物车.";
		} else {
			return ret.getString("msg");
		}
	}
	
	/**
	 * 从购物车中移除商品
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("delfromcart")
	public String delFromCart(@RequestParam(required=true) Long id){
		JSONObject ret = ShoppingCartHelper.delFromCart(id);
		if (ret.getString("code").equals(ResData.RES_CODE_SUCCESS)) {
			return "redirect:/myshopcart";
		} 
		
		return "redirect:/myshopcart";
	}
	
	@RequestMapping("clearcart")
	public String clearcart(){
		JSONObject ret = ShoppingCartHelper.clearCart();
		if (ret.getString("code").equals(ResData.RES_CODE_SUCCESS)) {
			return "redirect:/myshopcart";
		} 
		
		return "redirect:/myshopcart";
	}
	
	/****************************************************************************
	 * 购物车功能_结束
	 ***************************************************************************/
	
	

	
	@RequestMapping("searchresult")
	public String search(HttpServletRequest request, Model model){
		String pageNo = request.getParameter("pageNo");
		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "16";
		}
		
		String qtype= request.getParameter("qtype");
		if(StringUtils.isBlank(qtype)){
			qtype = "1";
		}
		
		String proName = request.getParameter("prodname");
		if(StringUtils.isBlank(proName)){
			proName = "";
		}
		String catelogId = request.getParameter("catelogid");
		if(StringUtils.isBlank(catelogId)){
			catelogId = "0";
		}
		else{
			JSONObject r = ProCateHelper.categoryPath(catelogId);
			if(r.getString("code").equals(ResData.RES_CODE_SUCCESS)){
				model.addAttribute("categoryPath",r.getJSONObject("data").getString("categoryPath"));
			}
		}
		JSONObject obj = ProductionsHelper.prodList(proName, qtype, catelogId, Integer.valueOf(pageNo), Integer.valueOf(pageSize));
		if(obj.getString("code").equals(ResData.RES_CODE_SUCCESS)){
			// 使用gson 转化返回的json字符串
			Gson gson = new GsonBuilder().create();
			List<Productions> retList = gson.fromJson(obj.getJSONObject("data").getString("productionsList"),
					new TypeToken<List<Productions>>() {
					}.getType());
			model.addAttribute("prodList", retList);
			model.addAttribute("pageNo", obj.getJSONObject("data").getInt("pageNo"));
			model.addAttribute("pageSize", obj.getJSONObject("data").getInt("pageSize"));
			model.addAttribute("count", obj.getJSONObject("data").getInt("count"));
			model.addAttribute("prodname", proName);
		}
		return "/order/search_result";
	}


	@RequestMapping("prodetail")
	public String proDetail(HttpServletRequest request, Model model){
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			try{
				JSONObject obj = ProductionsHelper.getProd(Long.valueOf(id));
				if(obj.getString("code").equals(ResData.RES_CODE_SUCCESS)){
					// 使用gson 转化返回的json字符串
					Gson gson = new GsonBuilder().create();
					Productions prod = gson.fromJson(obj.getJSONObject("data").getString("productions"), Productions.class);
					if(StringUtils.isNotBlank(prod.getIsPrescription())){
						prod.setIsPrescription(Constant.prescriptionEnum().get(prod.getIsPrescription()));
					}
					if(StringUtils.isNotBlank(prod.getIsEphedrine())){
						prod.setIsEphedrine(Constant.ephedrineEnum().get(prod.getIsEphedrine()));
					}

					if(StringUtils.isNotBlank(prod.getIsColdStorage())){
						prod.setIsColdStorage(Constant.coldStorageEnum().get(prod.getIsColdStorage()));
					}

					if(null !=prod.getProductionsCategory()){
						JSONObject r = ProCateHelper.categoryPath(prod.getProductionsCategory().getId().toString());
						if(r.getString("code").equals(ResData.RES_CODE_SUCCESS)){
							model.addAttribute("categoryPath",r.getJSONObject("data").getString("categoryPath"));
						}
					}
					model.addAttribute("prod", prod);
				}
			}
			catch(Exception e){
				
			}
		}
		return "/order/pro_detail";
	}

	@RequestMapping("getprice")
	@ResponseBody
	public String getPrice(HttpServletRequest request){
		//判断session是否失效，如失效需重新登录
		Long userId = SystemLoginUtils.getLoginUserId(request);
		if (null == userId){
			return "0.0";
		}
		
		//获取页面传过来的参数.  
		String prodId     = request.getParameter("id");//商品id
		String num        = request.getParameter("num");//商品数量
		
		//取客户id
		Long customerId = SystemLoginUtils.getCustomerId(request);
		Long bpId = SystemLoginUtils.getBusinesspersonId(request);
		JSONObject ret = ProductionsHelper.getProdPrice(prodId, num, bpId, customerId);//
		if (ret.getString("code").equals(ResData.RES_CODE_SUCCESS)) {
			return ret.getJSONObject("data").getString("customerPrice");
		} else {
			return "0.0";
		}
	}


	
	/****************************************************************************
	 *商品类别_开始  fediy
	 ***************************************************************************/
	/**
	 * 商品类别
	 * @param model
	 * @return
	 */
	@RequestMapping("procatelist")
	public String procateList(HttpServletRequest request,Model model){
		String url = "/order/pro_cate" ;
		String urltype = request.getParameter("urltype");
		if (null != urltype) {
			if(urltype.equals("pul") || urltype == "pul"){
				url = "/order/pro_cate_pul";
			}
		}
		JSONObject objpro = ProCateHelper.categoryList(null);
		// 使用gson 转化返回的json字符串
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		List<ProductionsCategory> proCateList = gson.fromJson(objpro.getJSONObject("data").getString("proCateList"),
				new TypeToken<List<ProductionsCategory>>() {
				}.getType());
		model.addAttribute("proCateList", proCateList);
		return url;
	}
	
	
	/****************************************************************************
	 *商品类别_结束
	 ***************************************************************************/
	
	
	
	/****************************************************************************
	 *信息发布_开始
	 ***************************************************************************/
	/**
	 * 
	 * 信息发布首页部分
	 * @param request
	 * @param model
	 * @return
	 */
	
	@RequestMapping("cmslistindex")
	public String cmsListIndex(HttpServletRequest request, Model model){
		String pageNo = request.getParameter("pageNo");
		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "5";
		}
		
		String url = "/cms1_index";
		
		/**
		 * cmsCategory a 、要闻回顾  ，   1、公告  ，其他值：该类别
		 *  loginType  1  没有登录客户所见  3 登录后客户所见
		 */
		String cmsCategory = request.getParameter("cmsCategory");
		String loginType = request.getParameter("loginType");
		if(cmsCategory=="a" || cmsCategory.equals("a"))
			url = "/cms2_index";
		
		JSONObject objpro =CmsHelper.cmsList(cmsCategory, loginType,Integer.valueOf(pageNo), Integer.valueOf(pageSize));
		// 使用gson 转化返回的json字符串
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		List<BusCms> cmsList = gson.fromJson(objpro.getJSONObject("data").getString("cmsList"),
				new TypeToken<List<BusCms>>() {
				}.getType());
		model.addAttribute("cmsList", cmsList);
		return url;
	}
	
	/**
	 * 
	 * 信息发布更多
	 * @param request
	 * @param model
	 * @return
	 */
	
	@RequestMapping("cmslist")
	public String cmsList(HttpServletRequest request, Model model){
		String pageNo = request.getParameter("pageNo");
		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "15";
		}
		
		/**
		 * cmsCategory a 、要闻回顾  ，   1、公告  ，其他值：该类别
		 *  loginType  1  没有登录客户所见  3 登录后客户所见
		 */
		String cmsCategory = request.getParameter("cmsCategory");
		String loginType = request.getParameter("loginType");
		
		JSONObject objpro =CmsHelper.cmsList(cmsCategory, loginType,Integer.valueOf(pageNo), Integer.valueOf(pageSize));
		// 使用gson 转化返回的json字符串
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		List<BusCms> cmsList = gson.fromJson(objpro.getJSONObject("data").getString("cmsList"),
				new TypeToken<List<BusCms>>() {
				}.getType());
		model.addAttribute("cmsList", cmsList);
		model.addAttribute("pageNo", objpro.getJSONObject("data").getInt("pageNo"));
		model.addAttribute("pageSize", objpro.getJSONObject("data").getInt("pageSize"));
		model.addAttribute("count", objpro.getJSONObject("data").getInt("count"));
		
		model.addAttribute("cmsCategory", cmsCategory);
		model.addAttribute("loginType",loginType);
		
		return "/cms_list";
	}
	
	
	@RequestMapping("cmsDetail")
	public String cmsDetail(HttpServletRequest request, Model model){
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			try{
				JSONObject obj = CmsHelper.cmsDetail(Long.valueOf(id));
				if(obj.getString("code").equals(ResData.RES_CODE_SUCCESS)){
					// 使用gson 转化返回的json字符串
					Gson gson = new GsonBuilder().create();
					BusCms busCms = gson.fromJson(obj.getJSONObject("data").getString("busCms"), BusCms.class);
					model.addAttribute("busCms", busCms);
				}
			}
			catch(Exception e){
				
			}
		}
		return "/cms_detail";
	}
	
	
	/****************************************************************************
	 *信息发布_结束
	 ***************************************************************************/

}
